package com.monolithiot.sso.common.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 2018/11/20 Create by 郭文梁
 * EntityUtil
 * 实体类工具
 *
 * @author 郭文梁
 * @date 2018/11/20
 */
public class EntityUtil {
    /**
     * 断言对象中的字段不为null，为null时抛出异常
     *
     * @param o      对象
     * @param fields 字段
     */
    public static void notNull(Object o, String... fields) {
        if (o == null) {
            throw new IllegalArgumentException("Parameter could not be null!");
        }
        for (String field : fields) {
            Object value;
            try {
                value = getFieldValue(o, field);
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }
            if (value == null) {
                throw new IllegalArgumentException(String.format("Field [%s] could not be null", field));
            }
        }
    }

    /**
     * 获取对象中字段的值
     *
     * @param o     对象
     * @param field 字段名称
     * @return 值
     */
    private static Object getFieldValue(Object o, String field) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = o.getClass().getMethod(getterMethodName(field));
        return method.invoke(o);
    }

    /**
     * 获取字段对象的getter方法名
     *
     * @param field 字段名称
     * @return getter方法名
     */
    private static String getterMethodName(String field) {
        String prefix = field.substring(0, 1);
        String suffix = field.substring(1);
        return "get" + prefix.toUpperCase() + suffix;
    }
}
